//
//  SudokuView.swift
//  GestureUnlocking
//
//  Created by Yinyin Zeng on 20/5/20.
//  Copyright © 2020 MaoYeYeDeJiangCuCha. All rights reserved.
//

import UIKit

class SudokuView: UIView {
    
    var passwordBlock:((_ pwd:String)->Bool)?
    
    var passwordStr:String = ""

    private var btnArr:[UIButton] = []//所有按钮
    private var linesBtnArr:[UIButton] = [] //需要连线的按钮
    private var currentPoin = CGPoint()//当前手指的位置
    private let screenShotImageView = UIImageView()//手势密码截图
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        
        self.addSubview(screenShotImageView)
        screenShotImageView.frame = CGRect(x: UIScreen.main.bounds.size.width * 0.5 - 50, y: -40, width: 100, height: 200)
        
        for i in 1...9 {
            //选择使用按钮，是因为它有很多状态
            let btn = UIButton()
            btn.tag = i
            btn.setBackgroundImage(UIImage(named: "gesture_node_normal"), for: .normal)
            btn.setBackgroundImage(UIImage(named: "gesture_node_highlighted"), for: .selected)
            btn.setBackgroundImage(UIImage(named: "gesture_node_error"), for: .disabled)
            btn.isUserInteractionEnabled = false//需要关闭按钮用户交互 否则触摸事件不穿透
            self.addSubview(btn)
            //把创建的按钮添加到数组中，方便管理
            btnArr.append(btn)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        
        //如果需要连线的数组为空 那么不执行下面操作
        if linesBtnArr.count == 0{
            return
        }
        
        //创建路径
        let path = UIBezierPath()
        
        for (index,btn) in linesBtnArr.enumerated() {
            //第一个为起始点
            if(index == 0){
                path.move(to: btn.center)
            }else{
                path.addLine(to: btn.center)
            }
        }
        
        path.addLine(to: self.currentPoin)
        
        //设置线的颜色
        UIColor.white.set()
         //设置线的线宽
        path.lineWidth = 10
        //设置线的连接处样式
        path.lineJoinStyle = .round
        //设置线的头部样式
        path.lineCapStyle = .round
        
        //渲染
        path.stroke()
    }

    override func layoutSubviews() {
        //一定不能忘记
        super.layoutSubviews()
        
        //计算九宫格的位置
        let iconWidth = 74
        let iconHeight = iconWidth
        let colCount = 3
        let marginTotal = Int(self.frame.size.width) - 80 - 3*iconWidth
        let margin = marginTotal / 4
        for (index,btn) in btnArr.enumerated(){
            let iconX = (index % colCount) * (margin + iconWidth) + margin + 40
            let iconY = (index / colCount) * (margin + iconWidth) + margin + 300
            btn.frame = CGRect(x: iconX, y: iconY, width: iconWidth, height: iconHeight)
        }
    }
    
    
    //手指点击的时候调用
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //获取触摸对象
        for touch in touches {
            //获取手指的位置
            let p = touch.location(in: self)
            //判断手指是否在按钮上
            for btn in btnArr {
                if(btn.frame.contains(p)){
                    //让按钮亮起来
                    btn.isSelected = true
                }
            }
        }
    }
    
    //手指移动的时候调用
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        //获取触摸对象
        for touch in touches {
            //获取手指的位置
            let p = touch.location(in: self)
            self.currentPoin = p
            //判断手指是否在按钮上
            for btn in btnArr {
                if(btn.frame.contains(p)){
                    //让按钮亮起来
                    btn.isSelected = true
                    if !linesBtnArr.contains(btn){
                        linesBtnArr.append(btn)
                    }
                }
            }
        }
        
        //重绘
        self.setNeedsDisplay()
    }
    
    //手指离开的时候调用
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        //关闭用户交互 防止连续连线
        self.isUserInteractionEnabled = false
        
        //修改最后手指的位置为需要连线的最后一个按钮的中心，解决最后一根线多出来的问题
        if let lastbtn = linesBtnArr.last{
            self.currentPoin = lastbtn.center
        }
        self.setNeedsDisplay()
        
        for btn in linesBtnArr {
            passwordStr += "\(btn.tag)"
        }
        
        //截图显示
        //开启图形上下文
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
        //获取图形上下文
        let contentext = UIGraphicsGetCurrentContext()
        //把视图内容放到上下文中 渲染
        self.layer.render(in: contentext!)
        //取图片
        screenShotImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭图形上下文
        UIGraphicsEndImageContext()
               
        
        if let block = passwordBlock{
            if !block(passwordStr){
                //所以需要画线的按钮都变成错误的样式
                for btn in linesBtnArr {
                    //取消选中效果
                    btn.isSelected = false
                    //按钮为不可用样式
                    btn.isEnabled = false
  
                    passwordStr += "\(btn.tag)"
                    
                    
                }
            }
        }
        
       
        
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            for btn in self.btnArr {
                //让按钮取消高亮
                btn.isSelected = false
                //按钮为可用样式
                btn.isEnabled = true
            }

            self.linesBtnArr.removeAll()
            self.setNeedsDisplay()
            
            //开启用户交互
            self.isUserInteractionEnabled = true
            //密码清空
            self.passwordStr = ""
        }
    }

}
